<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<CustomNavbar title="修改密码" />

		<!-- 页面内容 -->
		<view class="content">
			<!-- 密码修改表单 -->
			<view class="form-section">
				<view class="section-title">
					<text class="title-text">密码设置</text>
					<text class="title-icon">🔐</text>
				</view>
				
				<view class="form-card">
					<view class="form-item">
						<text class="form-label">当前密码</text>
						<input 
							class="form-input" 
							v-model="passwordForm.oldPassword" 
							placeholder="请输入当前密码" 
							type="password"
							maxlength="50"
							confirm-type="next"
							@input="onOldPasswordInput"
						/>
					</view>
					
					<view class="form-item">
						<text class="form-label">新密码</text>
						<input 
							class="form-input" 
							v-model="passwordForm.newPassword" 
							placeholder="请输入新密码（6-20位）" 
							type="password"
							maxlength="20"
							confirm-type="next"
							@input="onNewPasswordInput"
						/>
						<view v-if="passwordStrength" class="password-strength">
							<text class="strength-label">密码强度：</text>
							<view class="strength-bar">
								<view 
									class="strength-fill" 
									:class="passwordStrength.level"
									:style="{width: passwordStrength.percentage + '%'}"
								></view>
							</view>
							<text class="strength-text" :class="passwordStrength.level">{{passwordStrength.text}}</text>
						</view>
					</view>
					
					<view class="form-item">
						<text class="form-label">确认新密码</text>
						<input 
							class="form-input" 
							v-model="passwordForm.confirmPassword" 
							placeholder="请再次输入新密码" 
							type="password"
							maxlength="20"
							confirm-type="done"
							@input="onConfirmPasswordInput"
							@blur="validateConfirmPassword"
						/>
						<text v-if="confirmPasswordError" class="error-text">{{confirmPasswordError}}</text>
					</view>
				</view>
			</view>

			<!-- 密码规则提示 -->
			<view class="tips-section">
				<view class="section-title">
					<text class="title-text">密码规则</text>
					<text class="title-icon">💡</text>
				</view>
				
				<view class="tips-card">
					<view class="tip-item">
						<text class="tip-icon">✓</text>
						<text class="tip-text">密码长度为6-20位</text>
					</view>
					<view class="tip-item">
						<text class="tip-icon">✓</text>
						<text class="tip-text">建议包含字母、数字和特殊字符</text>
					</view>
					<view class="tip-item">
						<text class="tip-icon">✓</text>
						<text class="tip-text">避免使用常见密码</text>
					</view>
					<view class="tip-item">
						<text class="tip-icon">✓</text>
						<text class="tip-text">定期更换密码</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作区域 -->
		<view class="bottom-actions">
			<button class="action-btn cancel-btn" @click="cancelChange">
				<text class="btn-icon">↩️</text>
				<text class="btn-text">取消</text>
			</button>
			<button class="action-btn save-btn" @click="changePassword" :disabled="!canSubmit">
				<text class="btn-icon">🔒</text>
				<text class="btn-text">修改密码</text>
			</button>
		</view>
	</view>
</template>

<script>
	import { userAPI } from '@/utils/api.js'
	import CustomNavbar from '@/components/CustomNavbar.vue'
	
	export default {
		components: {
			CustomNavbar
		},
		data() {
			return {
				passwordForm: {
					oldPassword: '',
					newPassword: '',
					confirmPassword: ''
				},
				passwordStrength: null,
				confirmPasswordError: ''
			}
		},
		mounted() {
			console.log('修改密码页面已加载')
		},
		computed: {
			canSubmit() {
				return this.passwordForm.oldPassword.length >= 6 &&
					   this.passwordForm.newPassword.length >= 6 &&
					   this.passwordForm.confirmPassword.length >= 6 &&
					   this.passwordForm.newPassword === this.passwordForm.confirmPassword &&
					   !this.confirmPasswordError
			}
		},
		methods: {
			// 当前密码输入事件
			onOldPasswordInput(e) {
				console.log('当前密码输入:', e.detail.value)
				this.passwordForm.oldPassword = e.detail.value
			},
			
			// 新密码输入事件
			onNewPasswordInput(e) {
				console.log('新密码输入:', e.detail.value)
				this.passwordForm.newPassword = e.detail.value
				this.validateNewPassword()
			},
			
			// 确认密码输入事件
			onConfirmPasswordInput(e) {
				console.log('确认密码输入:', e.detail.value)
				this.passwordForm.confirmPassword = e.detail.value
			},
			
			// 验证新密码强度
			validateNewPassword() {
				const password = this.passwordForm.newPassword
				if (!password) {
					this.passwordStrength = null
					return
				}

				let score = 0
				let feedback = []

				// 长度检查
				if (password.length >= 8) score += 1
				else feedback.push('至少8位')

				// 包含小写字母
				if (/[a-z]/.test(password)) score += 1
				else feedback.push('包含小写字母')

				// 包含大写字母
				if (/[A-Z]/.test(password)) score += 1
				else feedback.push('包含大写字母')

				// 包含数字
				if (/\d/.test(password)) score += 1
				else feedback.push('包含数字')

				// 包含特殊字符
				if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) score += 1
				else feedback.push('包含特殊字符')

				// 计算强度
				let level, text, percentage
				if (score <= 2) {
					level = 'weak'
					text = '弱'
					percentage = 33
				} else if (score <= 3) {
					level = 'medium'
					text = '中'
					percentage = 66
				} else {
					level = 'strong'
					text = '强'
					percentage = 100
				}

				this.passwordStrength = { level, text, percentage, feedback }
			},

			// 验证确认密码
			validateConfirmPassword() {
				if (!this.passwordForm.confirmPassword) {
					this.confirmPasswordError = ''
					return
				}

				if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
					this.confirmPasswordError = '两次输入的密码不一致'
				} else {
					this.confirmPasswordError = ''
				}
			},

			// 修改密码
			async changePassword() {
				// 最终验证
				if (!this.canSubmit) {
					uni.showToast({
						title: '请检查输入信息',
						icon: 'none'
					})
					return
				}

				// 验证新密码长度
				if (this.passwordForm.newPassword.length < 6) {
					uni.showToast({
						title: '新密码长度至少6位',
						icon: 'none'
					})
					return
				}

				// 验证新密码不能与旧密码相同
				if (this.passwordForm.oldPassword === this.passwordForm.newPassword) {
					uni.showToast({
						title: '新密码不能与当前密码相同',
						icon: 'none'
					})
					return
				}

				uni.showModal({
					title: '确认修改',
					content: '确定要修改密码吗？修改后需要重新登录。',
					success: async (res) => {
						if (res.confirm) {
							await this.submitPasswordChange()
						}
					}
				})
			},

			// 提交密码修改
			async submitPasswordChange() {
				uni.showLoading({
					title: '修改中...'
				})

				try {
					const requestData = {
						oldPassword: this.passwordForm.oldPassword,
						newPassword: this.passwordForm.newPassword
					}

					console.log('修改密码请求数据:', requestData)
					await userAPI.changePassword(requestData)

					uni.showToast({
						title: '密码修改成功',
						icon: 'success'
					})

					// 延迟后跳转到登录页面
					setTimeout(() => {
						uni.showModal({
							title: '密码修改成功',
							content: '请使用新密码重新登录',
							showCancel: false,
							success: () => {
								// 清除登录状态
								uni.removeStorageSync('token')
								uni.removeStorageSync('user_info')
								
								// 跳转到登录页面
								uni.reLaunch({
									url: '/pages/login/login'
								})
							}
						})
					}, 1500)

				} catch (error) {
					console.error('密码修改失败:', error)
					let errorMessage = '密码修改失败'
					
					if (error.message) {
						console.log('错误信息:', error.message)
						if (error.message.includes('当前密码错误') || error.message.includes('密码不正确')) {
							errorMessage = '当前密码错误，请重新输入'
						} else if (error.message.includes('新密码')) {
							errorMessage = '新密码格式不符合要求'
						} else if (error.message.includes('网络')) {
							errorMessage = '网络连接失败，请检查网络'
						} else if (error.message.includes('401') || error.message.includes('未登录')) {
							errorMessage = '登录已过期，请重新登录'
						} else {
							errorMessage = error.message
						}
					} else {
						errorMessage = '网络连接失败，请检查网络连接'
					}

					uni.showToast({
						title: errorMessage,
						icon: 'none',
						duration: 3000
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 取消修改
			cancelChange() {
				if (this.passwordForm.oldPassword || this.passwordForm.newPassword || this.passwordForm.confirmPassword) {
					uni.showModal({
						title: '确认取消',
						content: '确定要放弃当前的修改吗？',
						success: (res) => {
							if (res.confirm) {
								uni.navigateBack()
							}
						}
					})
				} else {
					uni.navigateBack()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '../../uni.scss';
	
	.container {
		background: $cute-gradient-bg;
		min-height: 100vh;
		padding-bottom: 140rpx; // 为底部操作区域预留空间
		position: relative;
		z-index: 1;
	}
	
	.content {
		padding: 30rpx;
		margin-top: calc(var(--status-bar-height) + 88rpx); // 为导航栏预留空间
	}
	
	/* 通用区域样式 */
	.section-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 25rpx;
		padding: 0 10rpx;
	}
	
	.title-text {
		font-size: 32rpx;
		font-weight: 600;
		color: $cute-text-primary;
	}
	
	.title-icon {
		font-size: 28rpx;
	}
	
	/* 表单区域 */
	.form-section {
		margin-bottom: 40rpx;
	}
	
	.form-card {
		background: $cute-bg-secondary;
		border-radius: $cute-border-radius;
		padding: 30rpx;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
	}
	
	.form-item {
		margin-bottom: 35rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
	}
	
	.form-label {
		display: block;
		font-size: 26rpx;
		color: $cute-text-secondary;
		margin-bottom: 10rpx;
		font-weight: 500;
	}
	
	.form-input {
		width: 100%;
		height: 80rpx;
		padding: 0 25rpx;
		border: 3rpx solid $cute-border;
		border-radius: $cute-border-radius;
		font-size: 32rpx;
		background: $cute-bg-primary;
		transition: all 0.3s;
		box-sizing: border-box;
		color: $cute-text-primary;
		pointer-events: auto;
		user-select: text;
		line-height: 80rpx;
		
		&:focus {
			border-color: $cute-primary;
			background: white;
			outline: none;
			box-shadow: 0 0 0 6rpx rgba(144, 238, 144, 0.15);
			transform: translateY(-3rpx);
		}
		
		&::placeholder {
			color: $cute-text-tertiary;
			font-size: 30rpx;
		}
	}
	
	/* 密码强度指示器 */
	.password-strength {
		margin-top: 15rpx;
		display: flex;
		align-items: center;
		gap: 15rpx;
	}
	
	.strength-label {
		font-size: 24rpx;
		color: $cute-text-secondary;
	}
	
	.strength-bar {
		flex: 1;
		height: 8rpx;
		background: $cute-bg-tertiary;
		border-radius: 4rpx;
		overflow: hidden;
	}
	
	.strength-fill {
		height: 100%;
		transition: all 0.3s;
		border-radius: 4rpx;
		
		&.weak {
			background: linear-gradient(135deg, #ff6b6b, #ee5a52);
		}
		
		&.medium {
			background: linear-gradient(135deg, #ffd93d, #ff9500);
		}
		
		&.strong {
			background: linear-gradient(135deg, $cute-success, #51cf66);
		}
	}
	
	.strength-text {
		font-size: 24rpx;
		font-weight: 500;
		
		&.weak {
			color: #ff6b6b;
		}
		
		&.medium {
			color: #ff9500;
		}
		
		&.strong {
			color: $cute-success;
		}
	}
	
	.error-text {
		display: block;
		margin-top: 10rpx;
		font-size: 24rpx;
		color: $cute-error;
	}
	
	/* 提示区域 */
	.tips-section {
		margin-bottom: 40rpx;
	}
	
	.tips-card {
		background: $cute-bg-secondary;
		border-radius: $cute-border-radius;
		padding: 30rpx;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
	}
	
	.tip-item {
		display: flex;
		align-items: center;
		gap: 15rpx;
		margin-bottom: 20rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
	}
	
	.tip-icon {
		width: 30rpx;
		height: 30rpx;
		background: $cute-success;
		color: white;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20rpx;
		font-weight: bold;
		flex-shrink: 0;
	}
	
	.tip-text {
		font-size: 26rpx;
		color: $cute-text-secondary;
		line-height: 1.4;
	}
	
	/* 底部操作区域 */
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: white;
		padding: 30rpx;
		border-top: 2rpx solid $cute-divider;
		display: flex;
		gap: 20rpx;
		box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.1);
		z-index: 1000;
	}
	
	.action-btn {
		flex: 1;
		height: 80rpx;
		border-radius: $cute-border-radius;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
		font-size: 28rpx;
		font-weight: 500;
		transition: all 0.3s;
		box-shadow: $cute-button-shadow;
		pointer-events: auto;
		cursor: pointer;
		
		&.cancel-btn {
			background: $cute-bg-tertiary;
			color: $cute-text-secondary;
			border: 2rpx solid $cute-border;
			
			&:hover {
				background: $cute-bg-secondary;
				transform: translateY(-2rpx);
			}
		}
		
		&.save-btn {
			background: $cute-gradient-primary;
			color: white;
			
			&:hover:not(:disabled) {
				transform: translateY(-2rpx);
				box-shadow: 0 10rpx 30rpx rgba(144, 238, 144, 0.3);
			}
			
			&:disabled {
				background: $cute-bg-tertiary;
				color: $cute-text-tertiary;
				box-shadow: none;
				cursor: not-allowed;
			}
		}
		
		&:active:not(:disabled) {
			transform: translateY(0) scale(0.98);
		}
	}
	
	.btn-icon {
		font-size: 24rpx;
	}
	
	.btn-text {
		font-size: 28rpx;
	}
</style>
